<?php
class User_model_user extends Model {
    private $table_user = 'user';
    
    public function authenticate($username, $password) {
        $username = trim($username);
        $password = trim($password);
        if ($username && $password) {
            $row = $this->db->select_row(
                $this->table_user,
                array('id', 'passcode', 'created'),
                array('username' => $username)
            );
            $passcode = $row['passcode'];
            $created = $row['created'];
            
            $checkcode = $this->_generate_passcode($password, $created);
            if ($checkcode == $passcode) {
                return (int) $row['id'];
            }
        }
        return 0;
    }
    
    
    /* --- Private Functions --- */
    private function _generate_passcode($password, $created) {
        return '#$' . hash('sha256', $password. $this->_generate_salt($created));
    }
    
    
    private function _generate_salt($created) {
        $created = (string) $created;
        return substr(md5($created), 0, 16);
    }
    /* --- End Private Functions --- */
}
?>